import { _decorator, Component, instantiate, Node, Prefab, ScrollView } from 'cc';
import { UIHeader } from '../common/UIHeader';
import { EventManager } from '../event/EventManager';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { TabLayout } from '../common/TabLayout';
import { shopdata, shopOuter } from '../settings/const';
import { ShopIng } from '../entity/ShopIng';
import { MallGoods } from './MallGoods';
import ShopApi from '../api/ShopApi';
import { UserInfo } from '../common/UserInfo';
const { ccclass, property } = _decorator;

@ccclass('shop')
export class shop extends Component {
    @property(UIHeader)
    uiHeader: UIHeader;
    @property(ScrollView)
    scrollView: ScrollView
    /**商店列表 */
    @property(Node)
    content: Node

    @property(TabLayout)
    tabLayout: TabLayout;
    /**列表数据是array,inventory用来循环 */
    @property(Prefab)
    mallGoods: Prefab
    /**当前商城自定义数组 */
    itemList: ShopIng[] = []

    active:string = ''
    start() {
        this.uiHeader.setData('商城')
        EventManager.instance.on('商城close', () => {
            UIManager.instance.closeUI(PrefabEnum.Shop)
        }, this)


        this.tabLayout.setData(['获得道具', '获得元宝'])
        EventManager.instance.on('获得道具', this.getItem, this)
        EventManager.instance.on('获得元宝', this.getIngots, this)
        
        
        EventManager.instance.on(EventManager.EventType.ShopList, this.buy, this)

        if(this.active == '获得元宝'){
            this.getIngots()
        } else {
            this.getItem()
        }
    }

    getItem() {
        this.getList(0)
        this.tabLayout.setActiveByName('获得道具')
    }
    getIngots() {
        this.getList(1)
        this.tabLayout.setActiveByName('获得元宝')
    }

    async buy(e) {
        // index:0   兑换道具   index:1  外购
        if (e.index == 0) {
            let price = e.price.split(':')[1]
            /**获取背包元宝 */
            let diamond = UserInfo.instance.villageData.user.diamond
            // 判断所需元宝和背包元宝大小
            if (diamond >= price) {
                /**兑换接口返回结果 */
                UIManager.instance.showLoading()
                let isBuy = await ShopApi.BuyShopItem(e.typeId)
                UIManager.instance.closeLoading()
                if (isBuy.code == 0) {
                    UIManager.instance.modal('提示', '兑换道具成功！', false)
                    /**刷新userinfo状态数据内容 */
                    await UserInfo.instance.refreshVillageDetail()
                } else {
                    UIManager.instance.modal('提示', '兑换失败', false)
                }
            } else {
                //  元宝不足的情况下
                try {
                    await UIManager.instance.confrim({
                        title: '提示',
                        content: '元宝不足，兑换失败',
                        confrimText: '获得元宝'
                    })
                    this.getList(1)
                    this.tabLayout.setActiveByName('获得元宝')
                    console.log('点击了确定')
                } catch (error) {
                    console.log('点击了取消')
                }
            }
        } else if (e.index == 1) {
            UIManager.instance.showLoading()
            let res = await ShopApi.BuyItem(e.typeId)
            if (res.code == 0) {
                let order = {
                    cpId: res.data["cid"],
                    addr: res.data["addr"],
                    sn: res.data["sn"],
                }
                let ret = await ShopApi.fetching(encodeURIComponent(JSON.stringify(order)))
                if (ret.code == 0) {
                    window.location.href = `https://mt.gamegold.xin/#/pages/orderGame/index?f=order&auth=${JSON.stringify(ret.data)}`;
                }
            }

            UIManager.instance.closeLoading()
        }

    }

   

    getList(i: number) {
        if (i == 0) {
            this.itemList = ShopIng.createByShopIngObj(shopdata, 0)
        } else if (i == 1) {
            this.itemList = ShopIng.createByShopIngObj(shopOuter, 1)
        }
        // /**宝库库存根据循环新建标签 */
        this.content.destroyAllChildren()
        for (let item of this.itemList) {
            // this.itemList(this.itemList[0])
            let gameObject = instantiate(this.mallGoods)
            this.content.addChild(gameObject)
            gameObject.getComponent(MallGoods).setData(item)
        }

        this.scrollView.scrollToTop()

    }
}


